package com.example.demo.controller;

import com.example.demo.entity.Apple;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

/**
 * @author suliwei
 * @description: 测试 反射
 * @date 2025/2/27 10:16
 */
public class Reflect {

    public static void main(String[] args) throws Exception{

        //正常的调用
        Apple apple = new Apple();
        apple.setPrice(5);
        System.out.println("Apple Price:" + apple.getPrice());

        //使用反射调用
        Class clz = Class.forName("com.example.demo.entity.Apple");
        Method setPriceMethod = clz.getMethod("setPrice", int.class);
        Constructor appleConstructor = clz.getConstructor();
        Object appleObj = appleConstructor.newInstance();
        setPriceMethod.invoke(appleObj, 14);
        Method getPriceMethod = clz.getMethod("getPrice");
        System.out.println("Apple Price:" + getPriceMethod.invoke(appleObj));
    }

}
